package com.oodso.sell.ui.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.oodso.sell.model.util.HttpSubscriber;
import com.oodso.sell.utils.LogUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Observable;

/**
 * 项目名称：sell
 * 类描述：
 * 创建人：资拥
 * 创建时间：16/10/26 下午4:17
 * 修改人：资拥
 * 修改时间：16/10/26 下午4:17
 * 修改备注：
 */
public abstract class SellBaseFragment extends Fragment {

    private Unbinder mUnbinder;

    protected View rootView;
    
    private List<HttpSubscriber> subscriptions;

    protected abstract void initViews();

    public abstract void initData();

    protected abstract int getContentViewId();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(getContentViewId(), container, false);
        EventBus.getDefault().register(this);
        mUnbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();
        initData();
    }

    public void addSubscriptions(HttpSubscriber subscriber) {
        if (null == subscriptions)
            subscriptions = new ArrayList<>();
        subscriptions.add(subscriber);
    }

    protected void subscribe(Observable o, HttpSubscriber h) {
        o.subscribe(h);
        addSubscriptions(h);
    }

    public void unSubscribes() {
        if (null != subscriptions && subscriptions.size() > 0) {
            for (int i = 0; i < subscriptions.size(); i++) {
                if (!subscriptions.get(i).isUnsubscribed()) {
                    LogUtils.e("unSubscribes", "unsubscribe");
                    subscriptions.get(i).unsubscribe();
                    subscriptions.get(i).onError(new Throwable("请求取消"));
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        unSubscribes();
        super.onDestroyView();
        mUnbinder.unbind();
        EventBus.getDefault().unregister(this);
    }
}
